package com.hyts.xmlparser.convert.annotation;

import com.thoughtworks.xstream.converters.SingleValueConverter;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.xmlparser.annotation
 * author:Libo/Alex
 * create-date:2019-07-18 14:08
 * email:liboware@gmail.com
 * description:此类主要用于:
 */
public abstract class DateFieldConverter implements SingleValueConverter {


    public abstract String getPatternStr();


    @Override
    public String toString(Object obj) {
        if(Objects.nonNull(obj)){
            return LocalDateTime.ofInstant(((Date)obj).toInstant(), ZoneId.systemDefault()).
                    format(DateTimeFormatter.ofPattern(getPatternStr()));
        }
        return LocalDateTime.now().
                format(DateTimeFormatter.ofPattern(getPatternStr()));
    }

    @Override
    public Object fromString(String str) {
        //判断字符串是否为空
        if(null != str && !"".equals(str)){
            return LocalDateTime.parse(str,DateTimeFormatter.ofPattern(getPatternStr()));
        }
        return null;
    }

    @Override
    public boolean canConvert(Class type) {
        return Date.class.isAssignableFrom(type);
    }
}
